<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author YDZ
-->
<template>
  <div>
    <!-- <div v-if="!flag" class="title1">
      <div class="step1-form"
        style="width: 500px;border: 1px solid #aaa;padding: 30px 35px 30px 20px;border-radius: 10px;">
        <div style="font-weight: bold;font-size: 30px;text-align: center;margin-bottom: 50px;">
          选择公司
        </div>
        <BasicForm @register="registerForm2" style="padding: none;">
        </BasicForm>
        <div style="width: 100%;display: flex;justify-content: center;margin-top: 100px;padding-left: 15px;">
          <a-button style="width: 100%;" type="primary" @click="handleXzgs">下一步</a-button>
        </div>
      </div>
    </div> v-if="flag"-->
    <div class="title1">
      <div>
        <BasicTable @register="registerTable" @edit-change="rowChange">
          <template #tableTitle>
            <div style="display: flex;align-items: center;">
              <Icon :icon="getTitle.icon" class="m-1 pr-1" />
              <span class="mr-2"> 待送货区 </span>
              <!-- <span >【{{companyData.name}}】</span> -->
              <!-- <TreeSelect
              :value="companyData.code"
              :labelValue="companyData.name"
              :api="companyTreeData()"
              :params="{ isShowCode: true }"
              :canSelectParent="false"
              :treeCheckable="false"
              :immediate="true"
              :placeholder="'（公司编号）公司名称'"
            /> -->
              <BasicForm @register="registerForm2" style="margin-top: -5px;margin-bottom: -5px;width: 300px;">
              </BasicForm>
            </div>
          </template>
          <template #toolbar>
            <a-button type="success" ghost @click="handleAddBh()" v-auth="'srm:asn:create:edit'">
              <Icon icon="i-fluent:add-12-filled" /> {{ t('添加至备货区') }}
            </a-button>

            <a-button type="warning" ghost @click="handlefp" v-auth="'srm:asn:create:edit'">
              <Icon icon="i-fluent:add-12-filled" /> {{ t('自动分配') }}
            </a-button>

          </template>
          <template #firstColumn="{ record }">
            <a @click="handleForm({ id: record.id })">
              {{ record.unitname }}
            </a>
          </template>

          <template #summary>
            <TableSummary fixed>
              <TableSummaryRow>
                <TableSummaryCell :index="0" :col-span="2" align="center">
                  合计：
                </TableSummaryCell>

                <TableSummaryCell :index="2" :col-span="4">
                </TableSummaryCell>
                <TableSummaryCell :index="6" align="right">
                  {{totals[0]}}
                </TableSummaryCell>
                <TableSummaryCell :index="7" align="right">
                  {{totals[1]}}
                </TableSummaryCell>
                <TableSummaryCell :index="8" align="right">
                  {{totals[2]}}
                </TableSummaryCell>
                <TableSummaryCell :index="9" align="right">
                  {{totals[3]}}
                </TableSummaryCell>
                <TableSummaryCell :index="10" align="right">
                  {{totals[4]}}
                </TableSummaryCell>
                <TableSummaryCell :index="11" align="center">
                  <span style="color: red;font-weight: bold;">{{shNum}}</span>
                </TableSummaryCell>
                <TableSummaryCell :index="12" :col-span="7">
                </TableSummaryCell>
                <!-- <TableSummaryCell v-for="(item, index) in totals" :index="index" align="center"
                >{{ item }}
              </TableSummaryCell> -->
              </TableSummaryRow>
            </TableSummary>
          </template>
        </BasicTable>
      </div>
        <div class="lg:flex !mt-4" style="flex: 1;">
          <div class="lg:w-3/10 enter-y !mr-4" style="background: #fff;">
            <BasicTable @register="registerTable2" @row-click="handleRowClick">
              <template #tableTitle>
                <Icon :icon="getTitle.icon" class="m-1 pr-1" />
                <span> 分组区 </span>
              </template>
            </BasicTable>
          </div>
          <div class="lg:w-7/10 enter-y " style="background: #fff;">
            <BasicTable @register="registerTable3">
              <template #tableTitle>
                <Icon :icon="getTitle.icon" class="m-1 pr-1" />
                <span> 备货区</span>
                <span class="ml-2" style="font-weight: bold;color: red;">【说明：备货区记录仅24小时内有效；失效后将会自动清空】</span>
              </template>
              <template #toolbar>
                <!-- <a-button type="error" ghost @click="handleForm" v-auth="'puorder:poorder:edit'">
                  <Icon icon="ant-design:delete-outlined" /> {{ t('清除选择行') }}
                </a-button>
                <Popconfirm :title="t('是否确认订单？')" @confirm="handleRr()">
                <a-button type="success" ghost @click="handleModal" v-auth="'puorder:poorder:comfirm'">
                  <Icon icon="i-ant-design:check-outlined" /> {{ t('生成送货单') }}
                </a-button>
                </Popconfirm> -->
  
                <Dropdown placement="bottom" :trigger="['click']">
                  <a-button type="error" ghost @click.prevent v-auth="'srm:asn:create:edit'">
                    <Icon icon="ant-design:delete-outlined" /> {{ t('清除备货区') }}
                  </a-button>
                  <template #overlay>
                    <Menu>
                      <!-- v-if="hasPermission(['btn:proj:material:infoclqd'])" -->
                      <MenuItem @click="handlegx" v-if="hasPermission(['srm:asn:gx:br:delete'])">
                      <span>勾选记录清除</span>
                      </MenuItem>
                      <MenuDivider />
                      <MenuItem @click="handlegys" v-if="hasPermission(['srm:asn:gys:yh:delete'])">
                      <span>按供应商清除</span>
                      </MenuItem>
                      <MenuDivider />
                      <MenuItem @click="handlebr" v-if="hasPermission(['srm:asn:gx:br:delete'])">
                      <span>本人数据清除</span>
                      </MenuItem>
                      <MenuDivider />
                      <MenuItem @click="handlexzyh" v-if="hasPermission(['srm:asn:gys:yh:delete'])">
                      <span>选择用户清除</span>
                      </MenuItem>
                    </Menu>
                  </template>
                </Dropdown>
  
                <Dropdown placement="bottom" :trigger="['click']">
                  <a-button type="success" ghost @click.prevent v-auth="'srm:asn:create:edit'">
                    <Icon icon="i-ant-design:check-outlined" /> {{ t('生成送货单') }}
                  </a-button>
                  <template #overlay>
                    <Menu>
                      <MenuItem @click="handleGxsd">
                      <span>勾选生单</span>
                      </MenuItem>
                      <MenuDivider />
                      <MenuItem @click="handleYjsd">
                      <span>一键生单</span>
                      </MenuItem>
                    </Menu>
                  </template>
                </Dropdown>
              </template>
  
              <template #summary>
                <TableSummary fixed>
                  <TableSummaryRow>
                    <TableSummaryCell :index="0" :col-span="2" align="center">
                      合计：
                    </TableSummaryCell>
                    <TableSummaryCell :index="2" :col-span="5">
                    </TableSummaryCell>
                    <TableSummaryCell :index="8" align="center">
                      {{selQty}}
                    </TableSummaryCell>
                    <TableSummaryCell :index="9" :col-span="3">
                    </TableSummaryCell>
                  </TableSummaryRow>
                </TableSummary>
              </template>
            </BasicTable>
          </div>
        </div>
       
      <BasicModal v-bind="$attrs" @register="registerModal" title="自动分配" @ok="handleQr">
        <BasicForm @register="registerForm" />
      </BasicModal>

      <!-- 供应商 -->
      <ListSelect
        ref="listSelectRefGys"
        selectType="basVenSelect"
        :checkbox="false"
        @select="handleSelectGys"
        v-show="false"
      />

      <!-- 用户 -->
      <ListSelect
        ref="listSelectRefUser"
        selectType="empUserSelect"
        :checkbox="false"
        @select="handleSelectUser"
        v-show="false"
      />
    </div>
  </div>

</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsSrmPuorderOrderOrderAsnHList',
    components: { Menu, Dropdown, MenuItem: Menu.Item, MenuDivider: Menu.Divider },
  });
</script>
<script lang="ts" setup>
  import { unref, onMounted, computed, ref, defineComponent } from 'vue';
  import { TreeSelect, Menu, Dropdown } from 'ant-design-vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicTable, BasicColumn, useTable } from '/@/components/Table';
  import {
    puOrderPreDataNeedShListData,
    puOrderPreDataListData,
    puOrderPreDataGroupListData,
    puOrderPreDataSave,
    puOrderPreDataDelete,
    puOrderPreDataPushAsn
  } from '/@/api/srm/asn/presh/puOrderPreData';
  import { useDrawer, useDrawerInner, BasicDrawer } from '/@/components/Drawer';
  import { FormProps } from '/@/components/Form';
  import { PageWrapper } from '/@/components/Page';
  import { BasicModal, useModal } from '/@/components/Modal';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { ListSelect } from '/@/components/ListSelect';
  import {
    TableSummary,
    TableSummaryCell,
    TableSummaryRow,
  } from 'ant-design-vue';
  import { companyTreeData } from '/@/api/sys/company';
  import { NumEnum } from '/@/enums/defEnum';
  import { usePermission } from '/@/hooks/web/usePermission';
  const { hasPermission } = usePermission();
  import { useUserStore } from '/@/store/modules/user';
  const userStore = useUserStore();

  const { t } = useI18n('puorder.poorder');
  const { showMessage } = useMessage();
  const { meta } = unref(router.currentRoute);

  // const selectedRowRef = ref<string[]>([]);

  let companyData = ref({})

  let searchInfo3 = ref({})
  
  const listSelectRefGys = ref<any>(null);
  const listSelectRefUser = ref<any>(null);
    

  let flag = ref(false)
  const selectedRowRef = computed(() => {
    let arr = getSelectRows()
    return arr;
  });

  const shNum = computed(() => {
    let arr = getSelectRows()
    let sum = 0
    for (const record of arr) {
      let ntotalnum = record.editValueRefs.selQty.value
      sum += Number(ntotalnum);
    }
    return sum.toFixed(NumEnum.scaleSelQty);
  });

  const selQty = computed(() => {

    let sumselQty = 0
    for (const record of getDataSource3()) {
      const {
        selQty
      } = record;
      sumselQty += Number(selQty || 0);
    }
    return sumselQty.toFixed(NumEnum.scaleSelQty);
  });

  const getTitle = {
    icon: meta.icon || 'i-ant-design:book-outlined',
    // value: meta.title || t('订单变更记录'),
  };

  const searchForm: FormProps = {
    baseColProps: { lg: 6, md: 8 },
    labelWidth: 90,
    // showResetButton:false,
    schemas: [
      // {
      //   label: t('公司名称'),
      //   field: 'unitname',
      //   component: 'Input',
      // },
      {
        label: t('供应商'),
        field: 'parent.custName',
        component: 'Input',
        componentProps: {
          allowClear: true,
        },
      },
      {
        label: t('订单编号'),
        field: 'orderCode',
        component: 'Input',
        componentProps: {
          allowClear: true,
        },
      },
      {
        label: t('存货编码'),
        field: 'cinvcode',
        component: 'Input',
        componentProps: {
          allowClear: true,
        },
      },
      {
        label: t('存货名称'),
        field: 'cinvname',
        component: 'Input',
        componentProps: {
          allowClear: true,
        },
      },
      {
        label: t('规格'),
        field: 'cinvspec',
        component: 'Input',
        componentProps: {
          allowClear: true,
        },
      },
      {
        label: t('型号'),
        field: 'cinvtype',
        component: 'Input',
        componentProps: {
          allowClear: true,
        },
      },
      {
        label: t('单位'),
        field: 'measname',
        component: 'Input',
        componentProps: {
          allowClear: true,
        },
      },
      {
        label: t('订单日期'),
        field: 'parent.dorderdate',
        component: 'RangePicker',
      },
      {
        label: t('计划到货'),
        field: 'dplanarrvdate',
        component: 'RangePicker',
      },
      {
        label: t('采购员'),
        field: 'parent.psnName',
        component: 'Input',
        componentProps: {
          allowClear: true,
        },
      },
      {
        label: t('备注信息'),
        field: 'remarks',
        component: 'Input',
        componentProps: {
          allowClear: true,
        },
      },
      
    ],
    fieldMapToTime: [['dplanarrvdate', ['dplanarrvdate_gte', 'dplanarrvdate_lte']],['parent.dorderdate', ['parent.dorderdate_gte', 'parent.dorderdate_lte']]],
  };

  const tableColumns: BasicColumn[] = [



    {
      title: t('存货编码'),
      dataIndex: 'cinvcode',
      key: 'a.cinvcode',
      sorter: true,
      width: 130,
      align: 'left',
    },
    {
      title: t('存货名称'),
      dataIndex: 'cinvname',
      key: 'a.cinvname',
      sorter: true,
      width: 200,
      align: 'left',
    },
    {
      title: t('规格'),
      dataIndex: 'cinvspec',
      key: 'a.cinvspec',
      sorter: true,
      width: 120,
      align: 'left',
    },
    {
      title: t('型号'),
      dataIndex: 'cinvtype',
      key: 'a.cinvtype',
      sorter: true,
      width: 150,
      align: 'left',
    },

    {
      title: t('订单数'),
      dataIndex: 'puOrderExcute.iqty',
      // key: 'a.naccumstorenum',
      // sorter: true,
      width: 80,
      align: 'right',
    },
    {
      title: t('已准备数'),
      dataIndex: 'puOrderExcute.preShQty',
      width: 80,
      align: 'right',
    },
    {
      title: t('送货中数'),
      dataIndex: 'puOrderExcute.ingShQty',
      width: 80,
      align: 'right',
    },
    {
      title: t('已到货数'),
      dataIndex: 'puOrderExcute.arrQty',
      width: 80,
      align: 'right',
    },
    {
      title: t('待送货数'),
      dataIndex: 'puOrderExcute.syQty',
      width: 80,
      align: 'right',
      customCell: (record: Recordable) => {
        const color = '#eaf4e1';
        return {
          // innerHTML: record.testTextarea, // 原样输出，不进行html编码（例子）
          style: `background-color: ${color} !important`,
          // style: `color: ${color} !important;font-size: ${size};`,
        };
      },
    },
    {
      title: t('本次送货数'),
      dataIndex: 'selQty',
      width: 120,
      align: 'center',
      editComponent: 'InputNumber',
      editComponentProps: {
        min:0
      },
      edit: true,
      editable: true,
      customCell: (record: Recordable) => {
        const color = '#eaf4e1';
        return {
          // innerHTML: record.testTextarea, // 原样输出，不进行html编码（例子）
          style: `background-color: ${color} !important`,
          // style: `color: ${color} !important;font-size: ${size};`,
        };
      },
    },
    {
      title: t('单位'),
      dataIndex: 'measname',
      key: 'a.measname',
      sorter: true,
      width: 80,
      align: 'center',
    },
    {
      title: t('订单编号'),
      dataIndex: 'orderCode',
      key: 'a.order_code',
      sorter: true,
      width: 150,
      align: 'left',
    },
    {
      title: t('供应商'),
      dataIndex: 'parent.custName',
      width: 200,
      align: 'left',
    },
    {
      title: t('订单行号'),
      dataIndex: 'crowno',
      key: 'a.crowno',
      sorter: true,
      width: 100,
      align: 'left',
    },

    {
      title: t('订单日期'),
      dataIndex: 'parent.dorderdate',
      key: 'parent.dorderdate',
      sorter: true,
      width: 120,
      align: 'center',
    },
    {
      title: t('计划到货'),
      dataIndex: 'dplanarrvdate',
      key: 'a.dplanarrvdate',
      sorter: true,
      width: 120,
      align: 'center',
    },

    
    {
      title: t('采购员'),
      dataIndex: 'parent.psnName',
      width: 100,
      align: 'center',
    },
    {
      title: t('采购部门'),
      dataIndex: 'parent.deptName',
      width: 100,
      align: 'center',
    },

    {
      title: t('备注信息'),
      dataIndex: 'remarks',
      key: 'a.remarks',
      sorter: true,
      width: 230,
      align: 'left',
    },
   

  ];

  const table2Columns: BasicColumn[] = [

    {
      title: t('供应商'),
      dataIndex: 'venName',
      width: 100,
      align: 'left',
    },

    {
      title: t('业务流程'),
      dataIndex: 'busTypeName',
      width: 80,
      align: 'center',
    },
    {
      title: t('仓库'),
      dataIndex: 'wareName',
      width: 80,
      align: 'center',
    },
    {
      title: t('采购员'),
      dataIndex: 'cgName',
      width: 80,
      align: 'center',
    },
    {
      title: t('采购部门'),
      dataIndex: 'cgDeptName',
      width: 80,
      align: 'center',
    },
  ];

  const table3Columns: BasicColumn[] = [
   
    {
      title: t('存货编码'),
      dataIndex: 'poorderB.cinvcode',
      width: 130,
      align: 'left',
    },
    {
      title: t('存货名称'),
      dataIndex: 'poorderB.cinvname',
      width: 150,
      align: 'left',
    },
    {
      title: t('规格'),
      dataIndex: 'poorderB.cinvspec',
      width: 120,
      align: 'left',
    },
    {
      title: t('型号'),
      dataIndex: 'poorderB.cinvtype',
      width: 150,
      align: 'left',
    },
    {
      title: t('单位'),
      dataIndex: 'poorderB.measname',
      width: 80,
      align: 'center',
    },

    {
      title: t('本次送货数'),
      dataIndex: 'selQty',
      width: 100,
      align: 'center',
    },
    {
      title: t('订单编号'),
      dataIndex: 'orderCode',
      width: 120,
      align: 'left',
    },
    {
      title: t('订单日期'),
      dataIndex: 'poorder.dorderdate',
      width: 100,
      align: 'center',
    },
    // {
    //   title: t('采购员'),
    //   dataIndex: 'parent.psnName',
    //   width: 100,
    //   align: 'center',
    // },

    {
      title: t('备注信息'),
      dataIndex: 'remarks',
      width: 150,
      align: 'left',
    },
    // {
    //   title: t('供应商'),
    //   dataIndex: 'parent.custName',
    //   width: 200,
    //   align: 'left',
    // },
  ];

  const actionColumn: BasicColumn = {
    width: 160,
    actions: (record: Recordable) => [
      {
        icon: 'i-clarity:note-edit-line',
        title: t('编辑采购订单'),
        onClick: handleForm.bind(this, { id: record.id }),
        auth: 'puorder:poorder:edit',
      },
    ],
  };

  const [registerDrawer, { openDrawer }] = useDrawer();
  const [registerTable, { reload, getForm, getDataSource, getSelectRows, setSelectedRowKeys }] = useTable({
    api: puOrderPreDataNeedShListData,
    beforeFetch: (params) => {
      params.pkCorp = companyData.value.code || '-1'
      return params;
    },
    afterFetch: (list) => {
      list.forEach(element => {
        element.selQty = element.puOrderExcute.syQty
      });
      return list;
    },
    columns: tableColumns,
    //actionColumn: actionColumn,
    formConfig: searchForm,
    showTableSetting: true,
    useSearchForm: true,
    canResize: true,
    // scroll: {
    //   y: 250,
    // },
    maxHeight: 250,
    rowSelection: {
      type: 'checkbox',
    },
    immediate: false,

  });

  const [registerTable2, { reload: reload2 }] = useTable({
    api: puOrderPreDataGroupListData,
    beforeFetch: (params) => {
      params.pkCorp = companyData.value.code || '-1'
      return params;
    },
    columns: table2Columns,
    //actionColumn: actionColumn,
    formConfig: searchForm,
    showTableSetting: true,
    useSearchForm: false,
    // canResize: true, //表格是否flex布局
    // maxHeight: 600,
    immediate: false, //懒加载
    showIndexColumn: false,
    rowSelection: {
      type: 'radio',
    },
    rowKey:'id',
    pagination:false,
    isCanResizeParent:true
  });

  const [registerTable3, { reload: reload3, setTableData:setTableData3,getDataSource:getDataSource3,getSelectRows:getSelectRows3 }] = useTable({
    api: puOrderPreDataListData,
    beforeFetch: (params) => {
      params.pkCorp = companyData.value.code || '-1'
      return params;
    },
    columns: table3Columns,
    //actionColumn: actionColumn,
    formConfig: searchForm,
    showTableSetting: true,
    useSearchForm: false,
    // canResize: true, //表格是否flex布局
    // maxHeight: 600,
    
    immediate: false, //懒加载
    tableSetting: {
      redo: false
    },
    rowSelection: {
      type: 'checkbox',
    },
    isCanResizeParent:true
  });

  const [registerForm2, { validate: validate2,setFieldsValue:setFieldsValue2 }] = useForm({
    labelWidth: 80,
    schemas: [
      {
        label: t(''),
        field: 'code',
        fieldLabel: 'name',
        component: 'TreeSelect',
        componentProps: {
          api: companyTreeData,
          params: {
            isShowCode: true,
          },
          canSelectParent: false,
          placeholder: '（公司编号）公司名称',
          // allowClear: true,
          immediate: true,
          onChange: async (e) => {
            companyData.value.code = e
            await reload()
            reload2()
            setTableData3([])
            // setTimeout(() => {
            //   reload2()
            //   setTableData3([])
            // }, 500)
          },
        },
        // required: true,
      },

    ],
    baseColProps: { lg: 24, md: 24 },
  });

  const [registerForm, { resetFields, validate }] = useForm({
    labelWidth: 80,
    schemas: [
      {
        label: t(''),
        field: 'num',
        component: 'InputNumber',
        // componentProps: {
        //   placeholder: t('请输入分配数量'),
        //   min:0
        // },
        componentProps: ({ formModel }) => {
          return {
            placeholder: t('请输入分配数量'),
            min:0,
            onBlur: (e) => {
              formModel['num'] = formModel['num']?formModel['num'].toFixed(NumEnum.scaleSelQty):0
            },
          }
        },
        required: true,
      },
    ],
    baseColProps: { lg: 24, md: 24 },
  });

  const [registerModal, { openModal, closeModal, setModalProps }] = useModal();



  const totals = computed(() => {

    let sumiqty = 0
    let sumpreShQty = 0
    let sumingShQty = 0
    let sumarrQty = 0
    let sumsyQty = 0
    for (const record of getDataSource()) {
      console.log('record', record);
      // 计算总金额
      const {
        puOrderExcute: {
          iqty,
          preShQty,
          ingShQty,
          arrQty,
          syQty
        },
        // editValueRefs: {
        //   ntotalnum
        // },
      } = record;
      sumiqty += Number(iqty || 0);
      sumpreShQty += Number(preShQty || 0);
      sumingShQty += Number(ingShQty || 0);
      sumarrQty += Number(arrQty || 0);
      sumsyQty += Number(syQty || 0);
    }
    return [
      // sumnversion.toFixed(2),
      // sumntotalnum.toFixed(2),
      sumiqty,
      sumpreShQty,
      sumingShQty,
      sumarrQty,
      sumsyQty,
    ];
  });

  function handlefp() {
    let flag = true
    let cinvcode = getDataSource()[0].cinvcode
    let custName = getDataSource()[0].parent?.custName

    for (const record of getDataSource()) {
      if (record.cinvcode != cinvcode) {
        flag = false
      }
      if (record.parent?.custName != custName) {
        flag = false
      }
    }
    if (flag) {
      openModal(true, {});
      resetFields()
    } else {
      showMessage('页面请保证为同一存货和供应商!');
    }
  }

  async function handleQr() {
    let data = await validate();
    let keyArr = []
    for (const record of getDataSource()) {
      if (data.num > record.puOrderExcute.syQty) {
        record.selQty = record.puOrderExcute.syQty
      } else {
        record.selQty = data.num;
      }
      keyArr.push(record.id)
    }
    setSelectedRowKeys(keyArr || [])
    closeModal();
  }


  async function handleAddBh() {

    if (getSelectRows().length <= 0) {
      showMessage('请先勾选后添加备货区');
      return;
    }
    let list = getSelectRows().map(item => {
      return {
        orderBId: item.id,
        selQty: item.editValueRefs.selQty.value ? item.editValueRefs.selQty.value : 0,
        // pkCorp: item.pkCorp,
      }
    })
    const res = await puOrderPreDataSave({ pkCorp: companyData.value.code }, list);
    showMessage(res.message);
    reload()
    reload2()
    setTableData3([])
  }

  async function handlegx() {
    if (!companyData.value.code) {
      showMessage('请先选择公司！');
      return;
    }
    if (getSelectRows3().length <= 0) {
      showMessage('请先勾选后清除');
      return;
    }
    let data = {
      pkCorp: companyData.value.code,
      operType:'sel',
    }
    data.selIds = getSelectRows3().map((item)=> item.id).join(',')
    const res = await puOrderPreDataDelete(data);
    showMessage(res.message);
    // reload3({
    //   searchInfo: searchInfo3.value
    // })
    reload()
    reload2()
    setTableData3([])
  }

  async function handlegys() {
    if (!companyData.value.code) {
      showMessage('请先选择公司！');
      return;
    }
    listSelectRefGys.value.openSelectModal();
  }
  async function handleSelectGys(values: Recordable[]) {
    if (values.length == 0) {
      showMessage(t('请先选择供应商'));
      return;
    }
    let data = {
      pkCorp: companyData.value.code,
      operType:'vendor',
      venId:values[0].id
    }
    console.log(data);
    const res = await puOrderPreDataDelete(data);
    showMessage(res.message);
    reload()
    reload2()
    setTableData3([])
    listSelectRefGys.value.setSelectList([]);
  }



  async function handlebr() {
    if (!companyData.value.code) {
      showMessage('请先选择公司！');
      return;
    }
    let data = {
      pkCorp: companyData.value.code,
      operType:'curUser',
    }
    const res = await puOrderPreDataDelete(data);
    showMessage(res.message);
    reload()
    reload2()
    setTableData3([])
  }

  async function handlexzyh() {
    if (!companyData.value.code) {
      showMessage('请先选择公司！');
      return;
    }
    listSelectRefUser.value.openSelectModal();
  }
  async function handleSelectUser(values: Recordable[]) {
    if (values.length == 0) {
      showMessage(t('请先选择用户'));
      return;
    }
    let data = {
      pkCorp: companyData.value.code,
      operType:'selUser',
      userCode:values[0].userCode
    }
    const res = await puOrderPreDataDelete(data);
    showMessage(res.message);
    reload()
    reload2()
    setTableData3([])
    listSelectRefUser.value.setSelectList([]);
  }


  async function handleGxsd() {
    if (!companyData.value.code) {
      showMessage('请先选择公司！');
      return;
    }
    if (getSelectRows3().length <= 0) {
      showMessage('请先勾选后生单');
      return;
    }

    let data = {
      pkCorp: companyData.value.code,
      operType:'sel',
    }
    data.selIds = getSelectRows3().map((item)=> item.id).join(',')
    const res = await puOrderPreDataPushAsn(data);
    showMessage(res.message);
    reload()
    reload2()
    setTableData3([])
    router.push({
      path: '/srm/asn/vouch/asnH/list',
      query: {
      },
    });
  }
  async function handleYjsd() {
    if (!companyData.value.code) {
      showMessage('请先选择公司！');
      return;
    }
    let data = {
      pkCorp: companyData.value.code,
      operType:'all',
    }
    const res = await puOrderPreDataPushAsn(data);
    showMessage(res.message);
    reload()
    reload2()
    setTableData3([])
    router.push({
      path: '/srm/asn/vouch/asnH/list',
      query: {
      },
    });
  }


  function handleForm(record: Recordable) {
    openDrawer(true, record);
  }

  // 鼠标行点击事件，获取上表数据
  function handleRowClick(record: Recordable) {
    console.log(record);
    record.onEdit?.(true, false);
    searchInfo3.value = { 
        venId: record.venId,
        busType: record.busType,
        wareId: record.wareId,
        cgId: record.cgId,
        cgDeptId: record.cgDeptId,
    }
    reload3({
      searchInfo: searchInfo3.value
    });
  }

  function handleSuccess(record: Recordable) {
    reload({ record });
  }

  function handleSuccess2(record: Recordable) {
    reload2({ record });
  }


  onMounted(async () => {
    await  setFieldsValue2({
      code: userStore.getProjecte.code,
    })
    companyData.value.code = userStore.getProjecte.code || ''
    await reload()
    reload2()
    setTableData3([])
  });
  // async function handleBg() {
  //   await getForm().setFieldsValue({
  //     vordercode: router.currentRoute.value.query.vordercode,
  //   });
  //   reload();
  //   await getForm().setFieldsValue({
  //     vordercode: router.currentRoute.value.query.vordercode,
  //   });
  // }

  async function rowChange({ column, value, record }) {
    // let { editValueRefs: { ntotalnum } } = record;
    // if (value > record.nversion) {
    //   showMessage('本次送货数不能超过剩余数！');
    //   ntotalnum.value = record.nversion
    // }
    let { editValueRefs: { selQty } } = record;
    selQty.value = value.toFixed(NumEnum.scaleSelQty)
  }

  async function handleXzgs() {
    companyData.value = await validate2()
    flag.value = true
    setTimeout(() => {
      reload2()
      setTableData3([])
    }, 500)
  }
</script>
<style scoped>
  :deep(.jeesite-editable-cell__action) {
    display: none;
  }

  :deep(.edit-cell-align-center) {
    width: 100% !important;
  }

  .title1 {
    width: 100%;
    min-height: calc(100vh - 120px);
    display: flex;
    flex-direction: column;
    /* background: #ffffff;
    padding: 20px;
    display: flex;
    justify-content: center;
    align-items: center; */
  }
</style>